package org.geektimes.reactive.streams;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;

import java.util.LinkedList;
import java.util.List;

/**
 * @FileName: SimplePublisher
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2021/3/31 - 11:00
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class SimplePublisher<T> implements Publisher<T> {

    public List<Subscriber<T>> subscribers = new LinkedList<>();

    @Override
    public void subscribe(Subscriber<? super T> subscriber) {
        SubscriptionAdapter subscriptionAdapter = new SubscriptionAdapter(subscriber);
        subscriber.onSubscribe(subscriptionAdapter);

        subscribers.add(subscriptionAdapter.getSubscriber());
    }

    public void publish(T data) {
        subscribers.forEach(subscriber -> {
            subscriber.onNext(data);
        });
    }

    public static void main(String[] args) {
        BusinessSubscriber<Integer> subscriber = new BusinessSubscriber<>(5L);
        SimplePublisher<Integer> publisher = new SimplePublisher<>();
        publisher.subscribe(subscriber);

        for (int i = 0; i < 7; i++) {
            publisher.publish(i);
        }

    }

}
